上篇文章我們講過Validation驗證法,這次我們將Validation抽離,另外建立一個FormRequest來驗證request參數。
這個方法除了可以幫controller減個肥,還可以讓多個function共用一套驗證機制,增加程式復用性。
使用指令:
php artisan make:request {file name}
假設我建立file name 為 UserRequest檔案
結果:
路徑=app/Http/Requests/UserRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
}
上面是剛剛新增的request,還少了很多東西。首先,將authorize()
內return false;
改成true吧。
再來還需要加上messages()的function,我直接將完成品貼出來吧
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
class UserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'username' => 'required|max:16|alpha_dash',
'password' => 'required|regex:/[0-9a-zA-Z]{8}/',
'email' => 'required|email',
];
}
public function messages()
{
return [
'username.required' => 'username can not null. ',
'username.max' => 'username can not over 16 characters. ',
'username.alpha_dash' => 'username only have alpha-numeric characters, as well as dashes and underscores . ',
'password.regex' => 'password should over 8 characters and only 0-9,a-z,A-Z. ',
'password.required' => 'password should over 8 characters and only 0-9,a-z,A-Z. ',
'email.email' => 'The email must be a valid email address. ',
];
}
protected function failedValidation(Validator $validator)
{
$message = $validator->errors();
throw new HttpResponseException(response()->json(['status' => false, 'error' => $message->first()], 400));
}
}
rules和messages都和之前一樣直接複製貼上即可,重點是failedValidation() 這個function。這個function是繼承至FormRequest這個類別的,原本會導向別的頁面,而我們現在將其改寫,直接回傳json格式。
需要注意的是,加上這個function需再最上面引用
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
這樣就可以回傳我們想要的json格式了。
建立好FormRequest後,該怎麼再controller內使用呢?首先請再controller上方使用:
use App\Http\Requests\UserRequest;
將想要使用這個FormRequest的function內的Request改成新的Request名稱即可,例如:
將
public function register(Request $request)
()裏面的Request改成
public function register(UserRequest $request)
像這樣套上FormRequest的function就會有validation驗證功能了,validation就到此結束吧,Bye!